using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Emlyn.Website.Articles;
using Emlyn.Website.ArticlesPresentation;
using System.Collections.Generic;
using Emlyn.Common.Data.Configuration;
using wandev.AutoUpdate;
using System.IO;

public partial class SoftwareItem : EmlynPage
{
    Article lmainArticle = null;

    protected void Page_Load(object sender, EventArgs e)
    {
        const string C_DefaultArticle = "SoftwareItemMissing";

        string lArticleCode = null;

        if (Request.QueryString["code"] != null)
            lArticleCode = Request.QueryString["code"];

        if (lArticleCode == null)
            lArticleCode = C_DefaultArticle;

        ArticleQuery larticleQuery = new ArticleQuery();
        lmainArticle = larticleQuery.GetArticleByArticleCode(lArticleCode);


        if (lmainArticle != null)
        {
            UpdateSoftwareSubItems(lArticleCode);

            //
            // ArticleList details
            //
            PresentArticleDetail lpad = new PresentArticleDetail();
            lpad.aArticle = lmainArticle;
            lpad.Editable = false;
            //            lpad.CssClass = pnlBody.CssClass;
            pnlBody.Controls.Add(lpad);

            IList<Article> lChildArticles = larticleQuery.GetArticlesForParentArticleID(lmainArticle.ArticleID);
            if (lChildArticles.Count > 0)
            {
                PresentArticleList lpal = new PresentArticleList();
                lpal.aPresentArticleFactory = new PresentArticleDetailFactory();
                lpal.aPresentArticleFactory.aEditable = false;
                lpal.aArticleList = lChildArticles;
                //lpal.aPresentArticleFactory.aNavigateUrl =
                //    "Software.aspx?code=%ArticleCode%";

                //lpal.CssClass = pnlBody.CssClass;

                pnlBody.Controls.Add(lpal);
            }

            //IList<Article> lParentArticles = larticleQuery.GetArticlesForChildArticleID(larticle.ArticleID);
            //if (lParentArticles.Count > 0)
            //{
            //    PresentArticleList lpal = new PresentArticleList();
            //    lpal.aPresentArticleFactory = new PresentArticleTitleLinkFactory();
            //    lpal.aPresentArticleFactory.aEditable = false;
            //    lpal.aPresentArticleFactory.aNavigateUrl = Page.Request.Url.AbsolutePath + "?code=%ArticleCode%";
            //    lpal.Title = "Up to:";
            //    //lpal.CssClass = pnlRight.CssClass;
            //    lpal.aArticleList = lParentArticles;

            //    pnlRight.Controls.Add(lpal);
            //}
        }
        else
        {
            Label llbl = new Label();
            llbl.Text = "Article \"" + C_DefaultArticle + "\" not found.";
            pnlBody.Controls.Add(llbl);
        }
    }

    private void UpdateSoftwareSubItems(string aArticleCode)
    {
        ArticleQuery larticleQuery = new ArticleQuery();

        IList<Article> lchildArticles = larticleQuery.GetArticlesForParentArticleID(lmainArticle.ArticleID);

        List<VersionInformation> lversionInformationList = new List<VersionInformation>();
        RemoteLatestVersion lrlv = new RemoteLatestVersion(aArticleCode);

        string lfileLatestVersion = null;
        DateTime lLatestVersion = DateTime.MinValue;

        foreach(string lfile in System.IO.Directory.GetFiles(Config.GetFilePathPrefixString() + "\\software\\" + aArticleCode))
        {
            string lfileNoPath = System.IO.Path.GetFileName(lfile);

            bool lfound = false;
            foreach (Article lchildArticle in lchildArticles)
            {
                if (lchildArticle.ArticleName == lfileNoPath)
                {
                    lfound = true;

                    if (lLatestVersion < lchildArticle.LastChanged)
                    {
                        lLatestVersion = lchildArticle.LastChanged;
                        lfileLatestVersion = lfileNoPath;
                    }

                    break;
                }
            }

            if (!lfound)
            {
                Article lnewArticle = new Article();
                lnewArticle.ArticleName = lfileNoPath;
                lnewArticle.ArticleCode = GenerateCode();
                lnewArticle.ArticleContent = "New version " + aArticleCode + ", uploaded " + DateTime.Now.ToString();
                lnewArticle.Url = "software/" + aArticleCode + "/" + System.IO.Path.GetFileName(lfile);
                lnewArticle.LastChanged = DateTime.Now;

                ArticleMod larticleMod = new ArticleMod();
                larticleMod.Save(lnewArticle);
                larticleMod.AddArticleRelationship(lmainArticle.ArticleID, lnewArticle.ArticleID);

                lLatestVersion = lnewArticle.LastChanged;
                lfileLatestVersion = lfileNoPath;
            }

            // here we build the list of articles to use in generating the softwareversions file.
            VersionInformation lvi = new VersionInformation(aArticleCode);
            FileInfo lfi = new FileInfo(lfile);

            string ldownloadFile = 
                Page.Request.Url.Scheme + "://" +
                Page.Request.Url.GetComponents(UriComponents.HostAndPort, UriFormat.UriEscaped) + 
                ResolveUrl("software\\" + aArticleCode + "\\" + lfileNoPath);
            
            
            lvi.DownloadFile = new Uri(ldownloadFile);

            lvi.FileSize = lfi.Length;

            // The extraction of the version from the filename sucks shit. Gotta change this in the future.
            // It assumes a filename format like this: "...SomeStuff... vX1.X2.X3.X4.msi"
            // where what we want in VersionNumber is "X1.X2.X3.X4" .
            lvi.VersionNumber = GetVersionFromFilename(lfileNoPath);

            lversionInformationList.Add(lvi);
        }

        if (lversionInformationList.Count > 0)
        {
            foreach (VersionInformation lvi in lversionInformationList)
            {
                if (lvi.VersionNumber == GetVersionFromFilename(lfileLatestVersion))
                {
                    lrlv.LatestVersion = lvi;
                }
                else
                {
                    lrlv.PreviousVersions.Add(lvi);
                }
            }

            if (lrlv.LatestVersion != null)
            {
                lrlv.WriteXml(System.IO.Path.Combine(Config.GetFilePathPrefixString(), aArticleCode + "Versions.xml"));
            }
        }
    }

    private string GetVersionFromFilename(string lfileNoPath)
    {
        string retval = null;

        if (!String.IsNullOrEmpty(lfileNoPath))
        {
            string[] lfirstarr = lfileNoPath.Split(' ');

            retval = lfirstarr[lfirstarr.Length - 1]; // assume the entry after the last space is of the form "vX1.X2.X3.X4.msi"
            retval = retval.Substring(1, retval.Length - 5); // removes first char and last 4 chars, which are "v" and ".msi" respectively
        }

        return retval;
    }

    private string GenerateCode()
    {
        string lcode = ((new Random()).Next(99999999)).ToString();
        ArticleQuery laq = new ArticleQuery();

        while (laq.GetArticleByArticleCode(lcode) != null)
        {
            lcode = ((new Random()).Next(99999999)).ToString();
        };

        return lcode;
    }
}
